(function () {
    var calc = {
        /*
        函数，加法函数，用来得到精确的加法结果  
        说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
        参数：arg1：第一个加数；arg2第二个加数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数）
        调用：Calc.Add(arg1,arg2,d)  
        返回值：两数相加的结果
        */
        Add: function (arg1, arg2) {
        	arg1=arg1==undefined?0:arg1;
        	arg2=arg2==undefined?0:arg2;
            arg1 = arg1.toString(), arg2 = arg2.toString();
            var arg1Arr = arg1.split("."), arg2Arr = arg2.split("."), d1 = arg1Arr.length == 2 ? arg1Arr[1] : "", d2 = arg2Arr.length == 2 ? arg2Arr[1] : "";
            var maxLen = Math.max(d1.length, d2.length);
            var m = Math.pow(10, maxLen);
            var result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen));
            var d = arguments[2];
            return typeof d === "number" ? Number((result).toFixed(d)) : result;
        },
        /*
        函数：减法函数，用来得到精确的减法结果  
        说明：函数返回较为精确的减法结果。 
        参数：arg1：第一个加数；arg2第二个加数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数
        调用：Calc.Sub(arg1,arg2)  
        返回值：两数相减的结果
        */
        Sub: function (arg1, arg2) {
            arg1=arg1==undefined?0:arg1;
            arg2=arg2==undefined?0:arg2;
            return Calc.Add(arg1, -Number(arg2), arguments[2]);
        },
        /*
        函数：乘法函数，用来得到精确的乘法结果  
        说明：函数返回较为精确的乘法结果。 
        参数：arg1：第一个乘数；arg2第二个乘数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数)
        调用：Calc.Mul(arg1,arg2)  
        返回值：两数相乘的结果
        */
        Mul: function (arg1, arg2) {
            arg1=arg1==undefined?0:arg1;
            arg2=arg2==undefined?0:arg2;
            var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
            m = (r1.split(".")[1] ? r1.split(".")[1].length : 0) + (r2.split(".")[1] ? r2.split(".")[1].length : 0);
            resultVal = Number(r1.replace(".", "")) * Number(r2.replace(".", "")) / Math.pow(10, m);
            return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
        },
        /*
        函数：除法函数，用来得到精确的除法结果  
        说明：函数返回较为精确的除法结果。 
        参数：arg1：除数；arg2被除数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数)
        调用：Calc.Div(arg1,arg2)  
        返回值：arg1除于arg2的结果
        */
        Div: function (arg1, arg2) {
            arg1=arg1==undefined?0:arg1;
            arg2=arg2==undefined?0:arg2;
            var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
            m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0);
            resultVal = Number(r1.replace(".", "")) / Number(r2.replace(".", "")) * Math.pow(10, m);
            return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
        },
        /*
        百分号
         */
        Per: function (arg1, arg2) {
            var Divisor = Calc.Div(arg1, arg2,arguments[2]);
            if(isNaN(Divisor) || Divisor == Infinity || Divisor == 'Infinity' || arg2 == 0)
            {
                return '';
            }
            else
            {
                return Calc.Mul(Calc.Div(arg1, arg2,arguments[2]),100) +'%';
            }

        }
    };
    window.Calc = calc;
}());


function objIsNull(obj){
	if(obj == null || obj =="" || obj == undefined || obj == 'undefined' ){
		return false;
	}
	return true;	
}

//将单条数组拆分为多条。
function jsonSetSom(json,num){//num为拆分条目数
	//先计算json在图表中展示条目，因为实际展示数组是不显示子条目的，只显示子条目合计后的父条目
	var list_leng = 0;
	var for_each_flag = true;
	var father_name = '';
	var all_lenth = 0;
	for(i = 0 ;i<json.length;i++){
		all_lenth++;
		//如果是没有父科目的合计数+1
		if(json[i].isPar == 'N'){
			for_each_flag=true;
			list_leng++;
		}else{//如果有父科目也+1不过判别条件改为false
			if(father_name!=json[i].sticParName){//如果父科目不相等说明是另一条不同数据
				father_name=json[i].sticParName;
				for_each_flag=true;
			}
			if(for_each_flag){list_leng++;}//依据条件增加
			for_each_flag=false;
		}
	}
	//获取的list_leng还要再分。
	if(list_leng < num){
		return "error";
	}
	//每条数据的长度
	var emu = Math.floor(list_leng/num);
	//整除多出了的条目
	var yu = list_leng%num;
	return emu+"-"+yu+"-"+all_lenth;
}

function ajaxCreadExcel(url,json,title){
	var form = $("<form>");
    form.attr('style', 'display:none');
    form.attr('target', '');
    form.attr('method', 'post'); //请求方式
    form.attr('action', url);//请求地址

    var input1 = $('<input>');//将你请求的数据模仿成一个input表单
    input1.attr('type', 'hidden');
    input1.attr('name', 'json');//该输入框的name
    input1.attr('value',json);//该输入框的值

    var input3 = $('<input>');//将你请求的数据模仿成一个input表单
    input3.attr('type', 'hidden');
    input3.attr('name', 'title');//该输入框的name
    input3.attr('value',title);//该输入框的值
    
    $('body').append(form);
    form.append(input1);
    form.append(input3);
    form.submit();
    form.remove();
}

//依据规则拆分json					//可选参数,是否要在小计小项之前加上 "父科目头部_"的标识,默认为true,添加标识
function getJsonList(json,begin,num,addFather){
	if(addFather==undefined||addFather=='undefined'){
        addFather=true;
	}
	var sumNow = 0;
	var sumMon = 0;
	var sumYear = 0;
	var returnJosn = [];//返回数组
	var for_each_flag = true;
	var father_name = '';//父科目名称
	var lastMonMoney_price = 0;//科目合计
	var lastYearMoney_price = 0;//科目合计
	var nowMoney_price = 0;//科目合计
	var list_leng = 0;
	for(i = begin ;i<json.length;i++){
		if(json[i].isPar == 'N'){//判别是否有父科目
			if(father_name!=''){//如果父科目不为空说明上个科目有父科目,则添加合计项
                var newJson = {"isPar":"Y","lastMonMoney":lastMonMoney_price
                    ,"lastYearMoney":lastYearMoney_price,"nowMoney":nowMoney_price
                    ,"sticName":father_name,"sticParName":""};
                returnJosn.push(newJson);//添加;
			}
			father_name = '';

			//合计
			sumMon = Calc.Add(sumMon,json[i].lastMonMoney);
			sumYear = Calc.Add(sumYear,json[i].lastYearMoney);
			sumNow= Calc.Add(sumNow,json[i].nowMoney);

			//重置用于计算同一统计类别的统计数量
			lastMonMoney_price=0;
			lastYearMoney_price=0;
			nowMoney_price=0;

			returnJosn.push(json[i]);//加入数组
			for_each_flag=true;
			if(list_leng == num){
				if(father_name==""||father_name==null){
					father_name="合计";
				}
				var newJson = {"isPar":"Y","lastMonMoney":sumMon
					,"lastYearMoney":sumYear,"nowMoney":sumNow
					,"sticName":father_name,"sticParName":""};
				returnJosn.push(newJson);//添加;
				var reJson = {"json":returnJosn,"num":i};
				return reJson;
			}
			list_leng++;
		}else{

			if(father_name==''){//如果父科目为空则添加这些数据


				father_name=json[i].sticParName;
				/*lastMonMoney_price+=json[i].lastMonMoney;
				lastYearMoney_price+=json[i].lastYearMoney;
				nowMoney_price+=json[i].nowMoney;*/
			}
			if(father_name!=json[i].sticParName){//如果父科目不相等说明是另一条不同数据,将原数据加入
				//合计
                var childName = json[i].sticName.substring(0,json[i].sticName.indexOf("&"))//当前科目子名称
                if(childName=="减:累计折旧"||childName=="减:累计摊销"){
                    sumMon= Calc.Add(sumMon,-json[i].lastMonMoney);
                    sumYear = Calc.Add(sumYear,-json[i].lastYearMoney);
                    sumNow = Calc.Add(sumNow,-json[i].nowMoney);
                }else{
                    sumMon= Calc.Add(sumMon,json[i].lastMonMoney);
                    sumYear = Calc.Add(sumYear,json[i].lastYearMoney);
                    sumNow = Calc.Add(sumNow,json[i].nowMoney);
                }

				var newJson = {"isPar":"Y","lastMonMoney":lastMonMoney_price
					,"lastYearMoney":lastYearMoney_price,"nowMoney":nowMoney_price
					,"sticName":father_name,"sticParName":""};
				returnJosn.push(newJson);//添加
				list_leng++;
				//重置这些参数
				father_name=json[i].sticParName;
                if(childName=="减:累计折旧"||childName=="减:累计摊销"){
                    lastMonMoney_price=-json[i].lastMonMoney;
                    lastYearMoney_price=-json[i].lastYearMoney;
                    nowMoney_price=-json[i].nowMoney;
                }else{
                    lastMonMoney_price=json[i].lastMonMoney;
                    lastYearMoney_price=json[i].lastYearMoney;
                    nowMoney_price=json[i].nowMoney;
				}
				for_each_flag=true;
                var push_sticName = null;
                if(addFather==true){
                    push_sticName=json[i].sticParName+"_"+json[i].sticName;
				}else{
                	push_sticName=json[i].sticName;
				}
				returnJosn.push({"isPar":"Y","lastMonMoney":json[i].lastMonMoney
					,"lastYearMoney":json[i].lastYearMoney,"nowMoney":json[i].nowMoney
					,"sticName":push_sticName,
					"sticParName":json[i].sticParName});//添加
				//当已经存入的 父科目等于当前循环父科目说明 该数据应该合计

			}else if(father_name == json[i].sticParName){
                var childName = json[i].sticName.substring(0,json[i].sticName.indexOf("&"))//当前科目子名称
				//合计
				if(childName=="减:累计折旧"||childName=="减:累计摊销"){
                    sumMon= Calc.Add(sumMon,-json[i].lastMonMoney);
                    sumYear = Calc.Add(sumYear,-json[i].lastYearMoney);
                    sumNow = Calc.Add(sumNow,-json[i].nowMoney);

                    lastMonMoney_price = Calc.Add(lastMonMoney_price,json[i].lastMonMoney*-1);
                    lastYearMoney_price = Calc.Add(lastYearMoney_price,json[i].lastYearMoney*-1);
                    nowMoney_price = Calc.Add(nowMoney_price,json[i].nowMoney*-1);
				}else{
                    sumMon= Calc.Add(sumMon,json[i].lastMonMoney);
                    sumYear = Calc.Add(sumYear,json[i].lastYearMoney);
                    sumNow = Calc.Add(sumNow,json[i].nowMoney);

                    lastMonMoney_price = Calc.Add(lastMonMoney_price,json[i].lastMonMoney);
                    lastYearMoney_price = Calc.Add(lastYearMoney_price,json[i].lastYearMoney);
                    nowMoney_price = Calc.Add(nowMoney_price,json[i].nowMoney);
				}





                /*//如果为累计折旧或者累计摊销则使他们等于负数
                var childName = json[i].sticName.substring(0,json[i].sticName.indexOf("&"))
                if(childName=="减:累计折旧"||childName=="减:累计摊销"){
                    lastMonMoney_price = Calc.Mul(lastMonMoney_price,-1);
                    lastYearMoney_price = Calc.Mul(lastYearMoney_price,-1);
                    nowMoney_price = Calc.Mul(-nowMoney_price,-1);
                }else{

				}*/

                var push_sticName = null;
                if(addFather==true){
                    push_sticName=json[i].sticParName+"_"+json[i].sticName;
                }else{
                    push_sticName=json[i].sticName;
                }
				returnJosn.push({"isPar":"Y","lastMonMoney":json[i].lastMonMoney
					,"lastYearMoney":json[i].lastYearMoney,"nowMoney":json[i].nowMoney
					,"sticName":push_sticName,
					"sticParName":json[i].sticParName});//添加
				if(i==(json.length-1)){//如果最后一条数据，插入
					var newJson = {"isPar":"Y","lastMonMoney":lastMonMoney_price
							,"lastYearMoney":lastYearMoney_price,"nowMoney":nowMoney_price
							,"sticName":father_name,"sticParName":""};
					returnJosn.push(newJson);//添加
					
					//合计
					newJson = {"isPar":"Y","lastMonMoney":sumMon
							,"lastYearMoney":sumYear,"nowMoney":sumNow
							,"sticName":"合计","sticParName":""};
					returnJosn.push(newJson);//添加
					var reJson = {"json":returnJosn,"num":i};
					return reJson;
				}
				//如果下一条数据不是同一父科目，且这是最后一条能取出的数据则获取。
				if(father_name!=json[i+1].sticParName&&(list_leng==num)){
					var newJson = {"isPar":"Y","lastMonMoney":lastMonMoney_price
							,"lastYearMoney":lastYearMoney_price,"nowMoney":nowMoney_price
							,"sticName":father_name,"sticParName":""};
					returnJosn.push(newJson);//添加
					var reJson = {"json":returnJosn,"num":i};
					return reJson;
				}
				
			}
			
			
		}
        if(list_leng == num || (i+1) == json.length){
            var newJson = {"isPar":"Y","lastMonMoney":sumMon
                ,"lastYearMoney":sumYear,"nowMoney":sumNow
                ,"sticName":"合计","sticParName":""};
            returnJosn.push(newJson);//添加;
            var reJson = {"json":returnJosn,"num":i};
            return reJson;
        }
	}
}
//将json转化为导出专用的json
function getAllTableJosn(TitleJson,YearJson,MonJson,nowJosn){
	var newJson = [];
	var json = "[";
	for(i=0;i<TitleJson.length;i++){
		var title = TitleJson[i];
		if(TitleJson[i].indexOf("&") > 0){
			title = TitleJson[i].split("&")[0];
		}
		
		json+="{'sticName':"+title+","+"'nowMoney':"
			+nowJosn[i]+",'lastMonMoney':"+MonJson[i]
			+",'lastYearMoney':"+YearJson[i]+"}";
		if(i!=TitleJson.length-1){
			json+=",";
		}
	}
	return json+="]";
}

//获取表格中的json  用于保存的。
function getTableJson(){
	var resJson = "[";
	var lenj = $(".save_srfy_class").length;
	//遍历table中的tr
	$(".save_srfy_class").each(function(j){
		var len = $(this).find(".srfy_table_td_class").length;
		var thisId = $(this).children("td:first-child").children("div").attr("id").split("_")[1];
		if(thisId != undefined && thisId != 'undefined'){
			resJson+="{";
			//遍历tr中的td
		    $(this).find(".srfy_table_td_class").each(function(i){
		    		resJson+="'"+$(this).attr("id").split("_")[0]+"':";
			    	var str ="";
			    	//过滤非法字符
			    	if($(this).attr("id").split("_")[0] != 'sticId' ){
			    		str = $(this).text().replace(new RegExp("[^0-9\-\.]","g"),"");
			    		
			    	}else{
			    		str = $(this).attr("id").split("_")[1];
			    	}
			    	resJson+=str;
			    	resJson+=",";
		    })
		    resJson+="'sticId':"+thisId;
	    	resJson+="}";
		    if(j !=lenj-1){
		    	resJson+=",";
		    }
		}
	    
	});
	//如果最后一个字符是 , 去除
	var endStr = resJson.substr(resJson.length-1,1);
	if(endStr == ","){
		resJson=resJson.substring(0,resJson.length-1);
	}
	return resJson+="]";
	
}
//将生成的集合拆分为 图形工具生成的数据
function setAllJsonTo(json){
	var returnJson=[];
	var table = [];
	var graph = []
	var nowJosn=[];
	var MonJson=[];
	var YearJson=[];
	var TitleJson=[];
	//所有数组遍历放入---这个数据是图表统计用
	for(i=0;i<json.length;i++){
		nowJosn.push(json[i].nowMoney);
		MonJson.push(json[i].lastMonMoney);
		YearJson.push(json[i].lastYearMoney);
		TitleJson.push(json[i].sticName);
	}
	table ={"nowJosn":nowJosn,"MonJson":MonJson,"YearJson":YearJson,"TitleJson":TitleJson};
	nowJosn=[];
	MonJson=[];
	YearJson=[];
	TitleJson=[];
	//有父科目的过滤---这个数据是图形统计用
	for(i=0;i<json.length;i++){
		if(json[i].sticParName == 'null'||json[i].sticParName == ''){
			nowJosn.push(json[i].nowMoney);
			MonJson.push(json[i].lastMonMoney);
			YearJson.push(json[i].lastYearMoney);
			TitleJson.push(json[i].sticName.split("&")[0]);
		}
		
	}
	graph={"nowJosn":nowJosn,"MonJson":MonJson,"YearJson":YearJson,"TitleJson":TitleJson};
	returnJson=({"graph":graph,"table":table})
	
	return returnJson;
}

//设置光标移到末尾
/*function gbMonve(id,pos){
	var obj = document.getElementById(id);//obj.focus();
	
    if (obj.createTextRange) {//ie
        var rtextRange = obj.createTextRange();
        rtextRange.moveStart('character', pos);
        rtextRange.collapse(true);
        rtextRange.select();
    }
    else if (obj.selectionStart){//chrome "<input>"、"<textarea>"
        obj.selectionStart = pos;
    }else if(window.getSelection){
    	var range = window.getSelection();//创建range
        range.selectAllChildren(obj);//range 选择obj下所有子内容
        range.collapseToEnd();//光标移至最后    
    	//window.getSelection.selectAllChildren(obj);//range 选择obj下所有子内容
    	//window.getSelection.collapseToEnd();
    	return;
    	// 如果是文本节点则先获取光标对象
        var range = window.getSelection().getRangeAt(0);
        
        document.createRange().setSelectionRange(pos, pos);
        
        return;
        // 获取光标对象的范围界定对象，一般就是textNode对象
        var textNode = range.startContainer;
        // 获取光标位置
        var rangeStartOffset = range.startOffset;
    	
        // 光标移动到到原来的位置加上新内容的长度
        range.setStart(textNode, 0);
        var sel = window.getSelection();            

        var tempRange = document.createRange();
        try {
        	tempRange.setStart(obj.firstChild, obj.firstChild.length);

            sel.removeAllRanges();
            sel.addRange(tempRange); 
    	} catch(e) {
    	}
        
    }
}*/